package com.cloud.phone.utils;

import android.accessibilityservice.AccessibilityService;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityManager;

import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cloud.phone.service.AccessibilityAutoMainService;
import com.cloud.phone.tools.CmdTool;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class AccessibilityUtil {
    private final static String SCREEN_READER_INTENT_ACTION = "android.accessibilityservice.AccessibilityService";
    private final static String SCREEN_READER_INTENT_CATEGORY = "android.accessibilityservice.category.FEEDBACK_SPOKEN";
    private static final String TAG = "AccessibilityUtil";
    /**
     * 关闭无障碍服务
     *
     * @param context
     */
    public static void autoCloseAccessibilityService(Context context) {
        if (!Settings.System.canWrite(context)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
            return;
        }
        if (isStartAccessibilityServiceEnable(context)) {
            String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            ComponentName selfComponentName = new ComponentName(context.getPackageName(), AccessibilityAutoMainService.class.getCanonicalName());
            String flattenToString = selfComponentName.flattenToString();
            enabledServicesSetting = enabledServicesSetting.replace(":" + flattenToString, "");

            Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, enabledServicesSetting);
            //Settings.Secure.putInt(context.getContentResolver(),Settings.Secure.ACCESSIBILITY_ENABLED, 0);
            Log.d("zh", "autoCloseAccessibilityService: SETTING ACCESSIBILITY SUCCESS!");
        }
        return;
    }

    /**
     * 开启无障碍服务
     *
     * @param context
     */
    public static void autoOpenAccessibilityService(Context context) {
        if (!Settings.System.canWrite(context)) {
            ToastUtils.showShort("请求系统权限");
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
            return;
        }
        if (!isStartAccessibilityServiceEnable(context)) {
            ToastUtils.showShort("请求开启无障碍服务");
            String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            ComponentName selfComponentName = new ComponentName(context.getPackageName(), AccessibilityAutoMainService.class.getCanonicalName());
            String flattenToString = selfComponentName.flattenToString();
            if (enabledServicesSetting == null ||
                    !enabledServicesSetting.contains(flattenToString)) {
                enabledServicesSetting += ":" + flattenToString;
            }
            Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, enabledServicesSetting);
            Settings.Secure.putInt(context.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 1);
            ToastUtils.showShort("请求开启无障碍服务OK啦");
            Log.d("zh", "autoOpenAccessibilityService: SETTING ACCESSIBILITY SUCCESS!");
        }
    }

    /**
     * 判断无障碍服务是否开启
     *
     * @param context
     * @return
     */
    public static boolean isStartAccessibilityServiceEnable(Context context) {
        // 获取AccessibilityManager的实例
        AccessibilityManager accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
        // 判断无障碍权限是否已经开启
        boolean isAccessibilityEnabled = accessibilityManager.isEnabled();
        // 输出结果
        if (isAccessibilityEnabled) {
            LogUtils.d("Accessibility", "无障碍权限已经开启"+ true);
            return true;
        } else {
            LogUtils.d("Accessibility", "无障碍权限未开启" + false);
            return false;
        }
    }

    public static boolean isAccessibilitySettingsOn(String componentName, Context context) {
        if (TextUtils.isEmpty(componentName)) return false;
        int accessibilityEnable = 0;
        try {
            accessibilityEnable = Settings.Secure.getInt(context.getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED, 0);
        } catch (Exception ignored) {}
        try {
            if (accessibilityEnable == 1) {
                TextUtils.SimpleStringSplitter mStringColonSplitter =
                        new TextUtils.SimpleStringSplitter(':');
                String settingValue = Settings.Secure.getString(context.getContentResolver(),
                        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
                if (settingValue != null) {
                    mStringColonSplitter.setString(settingValue);
                    while (mStringColonSplitter.hasNext()) {
                        String accessibilityService = mStringColonSplitter.next();
                        if (accessibilityService.equalsIgnoreCase(componentName)) {
                            return true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void onForwardToAccessibility(Context context) {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        context.startActivity(intent);
    }

    public static boolean isAccessibilityEnabled(Context context) throws RuntimeException{
        if (context == null) {
            return false;
        }
        // 检查AccessibilityService是否开启
        AccessibilityManager am = (AccessibilityManager) context.getSystemService(android.content.Context.ACCESSIBILITY_SERVICE);
        boolean isAccessibilityEnabled_flag = am.isEnabled();
        return (isAccessibilityEnabled_flag);

    }

    public static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri = null;
        try {
            //Android7.0以上
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.cloud.phone.fileprovider", file);
            } else {
                uri = Uri.fromFile(file);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return uri;
    }

    private static boolean isScreenReaderActive(Context context) {

        // 通过Intent方式判断是否存在以语音播报方式提供服务的Service，还需要判断开启状态
        Intent screenReaderIntent = new Intent(SCREEN_READER_INTENT_ACTION);
        screenReaderIntent.addCategory(SCREEN_READER_INTENT_CATEGORY);
        List<ResolveInfo> screenReaders = context.getPackageManager().queryIntentServices(screenReaderIntent, 0);
        // 如果没有，返回false
        if (screenReaders == null || screenReaders.size() <= 0) {
            return false;
        }

        boolean hasActiveScreenReader = false;
        if (Build.VERSION.SDK_INT <= 15) {
            ContentResolver cr = context.getContentResolver();
            Cursor cursor = null;
            int status = 0;

            for (ResolveInfo screenReader : screenReaders) {
                cursor = cr.query(Uri.parse("content://" + screenReader.serviceInfo.packageName
                        + ".providers.StatusProvider"), null, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    status = cursor.getInt(0);
                    cursor.close();
                    // 状态1为开启状态，直接返回true即可
                    if (status == 1) {
                        return true;
                    }
                }
            }
        } else if (Build.VERSION.SDK_INT >= 26) {
            // 高版本可以直接判断服务是否处于开启状态
            for (ResolveInfo screenReader : screenReaders) {
                hasActiveScreenReader |= isAccessibilitySettingsOn(context, screenReader.serviceInfo.packageName + "/" + screenReader.serviceInfo.name);
            }

        } else {
            // 判断正在运行的Service里有没有上述存在的Service
            List<String> runningServices = new ArrayList<>();

            android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (android.app.ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                runningServices.add(service.service.getPackageName());
            }

            for (ResolveInfo screenReader : screenReaders) {
                if (runningServices.contains(screenReader.serviceInfo.packageName)) {
                    hasActiveScreenReader |= true;
                }
            }
        }

        return hasActiveScreenReader;
    }

    // To check if service is enabled
    private static boolean isAccessibilitySettingsOn(Context context, String service) {

        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        String settingValue = Settings.Secure.getString(
                context.getApplicationContext().getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        if (settingValue != null) {
            mStringColonSplitter.setString(settingValue);
            while (mStringColonSplitter.hasNext()) {
                String accessibilityService = mStringColonSplitter.next();
                if (accessibilityService.equalsIgnoreCase(service)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void execLinuxCommand() {
        String cmd = "am start -n com.cloud.phone/com.cloud.phone.MainActivity";
        //Runtime对象
        Runtime runtime = Runtime.getRuntime();
        try {
            Process localProcess = runtime.exec("su");
            OutputStream localOutputStream = localProcess.getOutputStream();
            DataOutputStream localDataOutputStream = new DataOutputStream(localOutputStream);
            localDataOutputStream.writeBytes(cmd);
            localDataOutputStream.flush();
            LogUtils.e(TAG, "设备准备重启");
        } catch (IOException e) {
            LogUtils.e(TAG, "DangerousUtil strLine:" + e.getMessage());
            e.printStackTrace();

        }
    }


    public static void killApp(AccessibilityService service,String appPackageName){
        // 如果事件类型为HOME键事件，则模拟返回键
        service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
        try {
            Thread.sleep(2000);
            CmdTool.getInstance().killApp(appPackageName);
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}